//
//  YGKGatherFlagController.m
//  GatherFlag
//
//  Created by CoderSUX on 16/7/5.
//  Copyright © 2016年 CoderSUX. All rights reserved.
//

#import "YGKGatherFlagController.h"
#import <CoreLocation/CoreLocation.h>
#import "Flag.h"
#import "Flag+CoreDataProperties.h"
#import "HMDataManager.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "YGKShowFlagController.h"
#import "YGKShowPathController.h"
#import "IWHttpTool.h"
#import "YGKMapViewController.h"

#define XCodeRate 0.002871
#define YCodeRate 0.002708
@interface YGKGatherFlagController ()<CLLocationManagerDelegate,NSFetchedResultsControllerDelegate>
@property (nonatomic) NSFetchedResultsController *fetchedResultsController;
@property(nonatomic, strong)CLLocationManager *mgr;
@property (weak, nonatomic) IBOutlet UITextField *flag_idTF;
@property (weak, nonatomic) IBOutlet UITextField *typeTF;
@property (weak, nonatomic) IBOutlet UILabel *x_codeLabel;
@property (weak, nonatomic) IBOutlet UILabel *y_codeLabel;
@property (weak, nonatomic) IBOutlet UITextField *road_idTF;
@property (weak, nonatomic) IBOutlet UITextField *loc_numberTF;
@property (weak, nonatomic) IBOutlet UITextField *descriptionTF;


@end

@implementation YGKGatherFlagController



- (NSFetchedResultsController *)fetchedResultsController {
    if (_fetchedResultsController) return _fetchedResultsController;
    
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Flag"];
    
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"x_code" ascending:YES];
    NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"y_code" ascending:YES];
    fetchRequest.sortDescriptors = @[sort,sort1];
    
    _fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[HMDataManager sharedManager].managedObjectContext sectionNameKeyPath:nil cacheName:nil];
    
    _fetchedResultsController.delegate = self;
    
    return _fetchedResultsController;
}


-(CLLocationManager *)mgr
{
    if (!_mgr) {
        _mgr = [[CLLocationManager alloc] init];
        _mgr.delegate = self;
        //定位精度设置为导航
        _mgr.desiredAccuracy = kCLLocationAccuracyBest;
    }
    
    return _mgr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.fetchedResultsController.fetchRequest.predicate = nil;
    [self.fetchedResultsController performFetch:NULL];
    //NSLog(@"%@",self.fetchedResultsController.fetchedObjects);
}

//开始定位
- (IBAction)startUpdateLocation:(UIButton *)sender
{
    if ([self.mgr respondsToSelector:@selector(requestAlwaysAuthorization)])
    {
        [self.mgr requestAlwaysAuthorization];
    }
    //开始定位
    [self.mgr startUpdatingLocation];
}

//停止定位
- (IBAction)stopUpdateLocation:(UIButton *)sender
{
    [self.mgr stopUpdatingLocation];
}

- (IBAction)saveToSystem:(UIButton *)sender
{
    if (self.flag_idTF.text.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入标识点的id"];
        return;
    }
    if (self.typeTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入标识点的类型,1为收费站,2为路径标识"];
        return;
    }
    if (self.road_idTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入路段的标识"];
        return;
    }
    
    if (self.loc_numberTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入桩号"];
        return;
    }
    
    if (self.descriptionTF.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入对该标识点的描述"];
        return;
    }
    
    
    Flag *flag = [NSEntityDescription insertNewObjectForEntityForName:@"Flag" inManagedObjectContext:[HMDataManager sharedManager].managedObjectContext];
    flag.flag_id = self.flag_idTF.text;
    flag.type = self.typeTF.text;
    flag.x_code = [NSNumber numberWithFloat:[self.x_codeLabel.text floatValue]];
    flag.y_code = [NSNumber numberWithFloat:[self.y_codeLabel.text floatValue]];
    flag.road_id = self.road_idTF.text;
    flag.loc_num = self.loc_numberTF.text;
    flag.des = self.descriptionTF.text;
    [[HMDataManager sharedManager] saveContext];
    //NSLog(@"保存成功");
    [SVProgressHUD showSuccessWithStatus:@"保存成功"];

}

- (IBAction)pushToServer:(UIButton *)sender
{
    
    //    6.4.9  路径上报接口
    //    接口名称  标识点数据上传
    //    请求地址  http://120.76.154.75/app/api/car/pointReport
    //
    //    输入参数
    //    名称    类型  说明                     参数要求
    //    token  字符  用户登录app后生成的唯一标识  必输
    //    station_id  数值类型数组  一组标识点id  必输，可以是所有未上报的点，也可以是全部的点（包括已上报的）
    //格式: sign = @"{\"token\":\"71adf4df-3bc4-444a-ba04-90f59df71dd2\",\"station_id\":\"1,2,3\"}";

    
    //    // 2.封装文件参数
    //    NSMutableArray *formDataArray = [NSMutableArray array];
    //    NSArray *images = [self.photosView totalImages];
    //    for (UIImage *image in images) {
    //        IWFormData *formData = [[IWFormData alloc] init];
    //        formData.data = UIImageJPEGRepresentation(image, 0.000001);
    //        formData.name = @"pic";
    //        formData.mimeType = @"image/jpeg";
    //        formData.filename = @"";
    //        [formDataArray addObject:formData];
    //    }
    //
    //http://120.76.154.75/app/api/car/pathPointReport
    //
    //    输入参数
    //    名称    类型  说明                     参数要求
    //    token  字符  用户登录app后生成的唯一标识  必输
    //    station_id  数值类型数组  一组标识点id  必输，可以是所有未上报的点，也可以是全部的点（包括已上报的）
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    NSString * strm = @"{\"mobile\":\"13671743863\",\"password\":\"1231\",\"plat_form\":\"3\",\"app_version\":\"1.0\"}";
//    
//    //strm = [NSString stringWithFormat:@"{\"token\":\"7990c519-7a9b-427e-9b03-e4ee7e1948b8\",\"point_id\":\"%ld,%ld\"}",[self.flag_idTF.text integerValue],[self.flag_idTF.text integerValue]];
//    params[@"sign"] = strm;
//    
//    NSString *url = @"http://120.76.154.75/app/api/member/login";
//    //url = @"http://120.76.154.75/app/api/car/pointReport";
//    
//    
//    [IWHttpTool postWithURL:url params:params success:^(id json)
//     {
////         NSDictionary *dict = json;
////         NSDictionary *data = dict[@"data"];
////         NSLog(@"%@", data[@"token"]);
//         
//     } failure:^(NSError *error) {
//         NSLog(@"%@",error);
//         
//     }];
//    
//    
}

- (IBAction)showMap:(id)sender {
    YGKMapViewController *mapVc = [[YGKMapViewController alloc] init];
    [self presentViewController:mapVc animated:YES completion:nil];
}

- (void)recognitionPath
{
    float min_xcode = [self.x_codeLabel.text floatValue] - XCodeRate;
    float max_xcode = [self.x_codeLabel.text floatValue] + XCodeRate;
    float min_ycode = [self.y_codeLabel.text floatValue] - YCodeRate;
    float max_ycode = [self.y_codeLabel.text floatValue] + YCodeRate;
    
    self.fetchedResultsController.fetchRequest.predicate = [NSPredicate predicateWithFormat:@"x_code > %f AND x_code < %f AND y_code > %f AND y_code < %f", min_xcode, max_xcode, min_ycode,max_ycode];
    [self.fetchedResultsController performFetch:NULL];
   
    if (self.fetchedResultsController.fetchedObjects.count > 0)
    {
        Flag *flag = self.fetchedResultsController.fetchedObjects.lastObject;
        NSLog(@"%@ %@",flag.flag_id,flag.type);
        
        
    }
}
//显示经过路径
- (IBAction)showPath:(UIButton *)sender
{
    YGKShowPathController *pathVc = [[YGKShowPathController alloc] init];
    [self presentViewController:pathVc animated:YES completion:nil];
}

- (IBAction)showFlag:(UIButton *)sender
{
    YGKShowFlagController *showFlagVC = [[YGKShowFlagController alloc] init];
    showFlagVC.fetchedResultsController = self.fetchedResultsController;
    [self presentViewController:showFlagVC animated:YES completion:nil];
}


#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = locations[0];

    self.x_codeLabel.text = [NSString stringWithFormat:@"%.6f",location.coordinate.longitude];
    self.y_codeLabel.text = [NSString stringWithFormat:@"%.6f",location.coordinate.latitude];
    //[self recognitionPath];
}

#pragma mark - NSFetchedResultsControllerDelegate
//- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
//    if (controller.fetchedObjects.count > 0)
//    {
//        Flag *flag = controller.fetchedObjects.lastObject;
//        NSLog(@"%@ %@",flag.flag_id,flag.type);
//    }
//    
//}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //[SVProgressHUD dismiss];
    [self.flag_idTF resignFirstResponder];
    [self.typeTF resignFirstResponder];
    [self.road_idTF resignFirstResponder];
    [self.loc_numberTF resignFirstResponder];
    [self.descriptionTF resignFirstResponder];
    //距离测试
//    float min_xcode = [self.x_codeLabel.text floatValue] - 0.002871;
//    float max_xcode = [self.x_codeLabel.text floatValue] + 0.002871;
//    float min_ycode = [self.y_codeLabel.text floatValue] - 0.002708;
//    float max_ycode = [self.y_codeLabel.text floatValue] + 0.002708;
//    CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:[self.y_codeLabel.text floatValue] longitude:max_xcode];
//    CLLocation *loc = [[CLLocation alloc] initWithLatitude:min_ycode longitude:[self.x_codeLabel.text floatValue]];
//    CLLocation *currentLoc = [[CLLocation alloc] initWithLatitude:[self.y_codeLabel.text floatValue] longitude:[self.x_codeLabel.text floatValue]];
    //[SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"东西方向距离 %f ,南北方向距离 %f",[loc1 distanceFromLocation:currentLoc], [loc distanceFromLocation:currentLoc]]];
    
}

@end
